package com.xyyy.xymusic;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.xyyy.xyplayer.XYTimeInfoBean;
import com.xyyy.xyplayer.listener.XYOnCompleteListener;
import com.xyyy.xyplayer.listener.XYOnErrorListener;
import com.xyyy.xyplayer.listener.XYOnLoadListener;
import com.xyyy.xyplayer.listener.XYOnPauseResumeListener;
import com.xyyy.xyplayer.listener.XYOnPreparedListener;
import com.xyyy.xyplayer.listener.XYOnRecordTimeListener;
import com.xyyy.xyplayer.listener.XYOnTimeInfoListener;
import com.xyyy.xyplayer.listener.XYOnValumeDBListener;
import com.xyyy.xyplayer.log.LogUtil;
import com.xyyy.xyplayer.muteenum.MuteEnum;
import com.xyyy.xyplayer.player.XYplayer;
import com.xyyy.xyplayer.utils.TimeUtil;

import java.io.File;
import java.util.List;

import io.reactivex.functions.Consumer;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private SeekBar seekProgress;
    private Button btPlay;
    private Button btPause;
    private XYplayer xYplayer;
    private Button btResume;
    private Button btStop;
    private SeekBar seekVolume;
    private TextView tvVolume;


    String url = Environment.getExternalStorageDirectory()+"/xjw.mp3";
//    String url = "http://mpge.5nd.com/2015/2015-11-26/69708/1.mp3";
    private TextView tvTime;
    private int totalTime;
    private int position = 0;
    //滑动的时候设置时间不跳转
    private boolean isSeekBar = false;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        seekProgress = findViewById(R.id.seek_progress);
        btPlay = findViewById(R.id.bt_play);
        btPause = findViewById(R.id.bt_pause);
        btResume = findViewById(R.id.bt_resume);
        tvTime = findViewById(R.id.tv_time);

        btStop = findViewById(R.id.bt_stop);
        seekVolume = findViewById(R.id.seek_volume);
        tvVolume = findViewById(R.id.tv_volume);

        btPlay.setOnClickListener(this);
        btPause.setOnClickListener(this);
        btResume.setOnClickListener(this);
        btStop.setOnClickListener(this);
        xYplayer = XYplayer.getInstance();
        //设置音量
        xYplayer.setVolume(50);
        xYplayer.setMute(MuteEnum.MUTE_LEFT);
        xYplayer.setPitch(1.5f);
        xYplayer.setSpeed(1.5f);

        tvVolume.setText("音量: " + xYplayer.getVolumePercent() + "%");
        seekVolume.setProgress(xYplayer.getVolumePercent());

        xYplayer.setXyOnPreparedListener(new XYOnPreparedListener() {
            @Override
            public void onPrepared() {

                LogUtil.d("准备好了 onPrepared 回调成功");
                xYplayer.start();
            }

        });

        xYplayer.setXyOnLoadListener(new XYOnLoadListener() {
            @Override
            public void onLoad(boolean load) {
                if (load) {
                    LogUtil.d("加载中");
                } else {
                    LogUtil.d("播放中");
                }
            }
        });

        xYplayer.setXyOnPauseResumeListener(new XYOnPauseResumeListener() {
            @Override
            public void onPause(boolean pause) {
                if (pause) {
                    LogUtil.d("暂停中");
                } else {
                    LogUtil.d("播放中");
                }
            }
        });

        xYplayer.setXyOnTimeInfoListener(new XYOnTimeInfoListener() {
            @Override
            public void onTimeInfo(XYTimeInfoBean timeInfoBean) {
                RxBus.getInstance().post(timeInfoBean);
            }
        });

        xYplayer.setXyOnErrorListener(new XYOnErrorListener() {
            @Override
            public void onError(int code, String msg) {
                LogUtil.d("code = " + code + " msg = " + msg);
            }
        });

        xYplayer.setXyOnCompleteListener(new XYOnCompleteListener() {
            @Override
            public void onComplete() {
                LogUtil.d("播放完成");
            }
        });

        xYplayer.setXyOnValumeDBListener(new XYOnValumeDBListener() {
            @Override
            public void onDbValue(int db) {
//                LogUtil.d("当前音量分贝值: = "+db);
            }
        });
        xYplayer.setXyOnRecordTimeListener(new XYOnRecordTimeListener() {
            @Override
            public void onRecordTime(int recordTime) {
                LogUtil.d("当前录制的时间 = "+recordTime);
            }
        });

        seekProgress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (xYplayer.getDuration() > 0 && isSeekBar) {
                    position = xYplayer.getDuration() * progress / 100;
                    LogUtil.d("position = " + position);
                    LogUtil.d("xYplayer.getDuration() " + xYplayer.getDuration());
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                isSeekBar = true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //滑动结束之后 seek
                xYplayer.seek(position);
                isSeekBar = false;
            }
        });

        seekVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                xYplayer.setVolume(progress);
                tvVolume.setText("音量: " + xYplayer.getVolumePercent() + "%");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        RxBus.getInstance().doSubscribe(this, XYTimeInfoBean.class, new Consumer<XYTimeInfoBean>() {
            @Override
            public void accept(XYTimeInfoBean bean) throws Exception {
                // 修改完数据，刷新
                if (!isSeekBar && bean != null) {
                    totalTime = bean.getTotalTime();
                    tvTime.setText(TimeUtil.secdsToDateFormat(bean.getCurrentTime(), bean.getTotalTime())
                            + "/" + TimeUtil.secdsToDateFormat(bean.getTotalTime(), bean.getTotalTime()));
//                    float p = (bean.getCurrentTime() / (float) bean.getTotalTime());
//                    int p1 = (int) (p * 100);
//                    LogUtil.d("进度: float = "+p);
//                    LogUtil.d("进度: int = "+p1);

                    setSeekProgress(bean.getCurrentTime() * 100 / bean.getTotalTime());
                }
            }
        });
    }

    public void setSeekProgress(int progress) {
        seekProgress.setProgress(progress);
    }

    private void playMusic(String url) {
        xYplayer.setSource(url);
        xYplayer.prepared();
    }


//    private void pauseMusic(){
//        musicUtil.pauseVoice();
//    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_play:
                playMusic(url);
//                    playMusic("/sdcard/myhome.mp3");
                break;
            case R.id.bt_pause://暂停
                xYplayer.pause();
                break;
            case R.id.bt_resume://播放
                xYplayer.resume();

                break;
            case R.id.bt_stop://停止
                LogUtil.d("按下停止");
                xYplayer.stop();

                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public void seek(View view) {
        xYplayer.seek(215);
    }

    //切换
    public void next(View view) {
        xYplayer.playNext("http://ngcdn004.cnr.cn/live/dszs/index.m3u8");
    }

    //左声道
    public void left(View view) {
        xYplayer.setMute(MuteEnum.MUTE_LEFT);
    }

    //右声道
    public void right(View view) {
        xYplayer.setMute(MuteEnum.MUTE_RIGHT);

    }

    //立体声
    public void center(View view) {

        xYplayer.setMute(MuteEnum.MUTE_CENTER);
    }

    public void normal(View view) {
        xYplayer.setSpeed(1.0f);
        xYplayer.setPitch(1.0f);
    }

    public void speedpitch(View view) {
        xYplayer.setSpeed(1.5f);
        xYplayer.setPitch(1.5f);
    }

    public void pitch(View view) {
        xYplayer.setSpeed(1.0f);
        xYplayer.setPitch(1.5f);
    }

    public void speed(View view) {
        xYplayer.setSpeed(1.5f);
        xYplayer.setPitch(1.0f);
    }


    public void start_record(View view) {
        LogUtil.d("Environment.getExternalStorageDirectory() = "+Environment.getExternalStorageDirectory());
        xYplayer.startRecord(new File(Environment.getExternalStorageDirectory()+"/test1.aac"));

    }


    public void pause_record(View view) {
        xYplayer.pauseRecord();
    }

    public void goon_record(View view) {
        xYplayer.resumeRecord();
    }

    public void stop_record(View view) {
        xYplayer.stopRecord();
    }

    public void jump_cut(View view) {
        startActivity(new Intent(this,CutActivity.class));
    }

    public void isHasPermission() {
        if (XXPermissions.isHasPermission(MainActivity.this,  Permission.READ_EXTERNAL_STORAGE,
                Permission.WRITE_EXTERNAL_STORAGE, Permission.RECORD_AUDIO)) {
            Toast.makeText(MainActivity.this, "已经获取到权限，不需要再次申请了", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(MainActivity.this, "还没有获取权限", Toast.LENGTH_SHORT).show();
            requestPermission();
        }
//        if (XXPermissions.isHasPermission(this, Permission.RECORD_AUDIO)) {
//            Toast.makeText(MainActivity.this, "已经获取到音频", Toast.LENGTH_SHORT).show();
//        }else{
//            Toast.makeText(MainActivity.this, "已经获取到存储权限，不需要再次申请了", Toast.LENGTH_SHORT).show();
//        }
    }
    public void requestPermission() {
        XXPermissions.with(this)
                //.constantRequest() //可设置被拒绝后继续申请，直到用户授权或者永久拒绝
//                .permission(Permission.SYSTEM_ALERT_WINDOW, Permission.REQUEST_INSTALL_PACKAGES) //支持请求6.0悬浮窗权限8.0请求安装权限
                .permission(Permission.READ_EXTERNAL_STORAGE,
                        Permission.WRITE_EXTERNAL_STORAGE, Permission.RECORD_AUDIO) //不指定权限则自动获取清单中的危险权限
                .request(new OnPermission() {

                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        if (isAll) {
                            Toast.makeText(MainActivity.this, "获取权限成功", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(MainActivity.this, "获取权限成功，部分权限未正常授予", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        if (quick) {
                            Toast.makeText(MainActivity.this, "被永久拒绝授权，请手动授予权限", Toast.LENGTH_SHORT).show();
                            //如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.gotoPermissionSettings(MainActivity.this);
                        } else {
                            Toast.makeText(MainActivity.this, "获取权限失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }
}
